import pickle

from config import JID, JID_password, vk_token, vk_version

import requests

from slixmpp import ClientXMPP

try:
    f = open('user_data', 'rb')
    user_domain_list = pickle.load(f)
    f.close()
    print('file load')
except Exception:
    print('file not found')
    user_domain_list = {}


class Vinni(ClientXMPP):

    def __init__(self, jid, password):
        ClientXMPP.__init__(self, jid, password)
        self.add_event_handler('session_start', self.session_start)
        self.add_event_handler('message', self.message_handler)

    def session_start(self, event):
        self.send_presence()
        self.get_roster()
        print('session started')

    def geter(self, msg, sender, count_posts=10):
        global user_domain_list
        for domain in user_domain_list[sender]:
            try:
                response = requests.get(f'https://api.vk.com/method/wall.get?domain={domain}&count={count_posts}&access_token={vk_token}&v={vk_version}')
                save_response = response.json()
                get_data = save_response['response']['items']
                for items in get_data:
                    if items['marked_as_ads'] == 1:
                        continue
                    if items['id'] in user_domain_list[sender][domain]:
                        continue
                    else:
                        msg.reply(f"_____\n*{domain}*:\n{items['text']}\n _____").send()
                        user_domain_list[sender][domain].append(items['id'])
            except Exception:
                msg.reply(f'cant get data from {domain}').send()

    def undefined_command(self, msg, sender):
        msg.reply(f"Hi, {sender}, I'm Vinni. I can get posts from VK and send it u. These features are now available to you: \n /add - add one or more domain\n /up - get new posts\n /rm - remove one or more domain\n /show - show your domains").send()

    def add(self, msg, sender):
        global user_domain_list

        message_body = msg['body'][5:].strip().split()
        if len(message_body) == 0:
            msg.reply('please enter domain(s) after /add').send()
        else:
            pre_list = {}
            for i in message_body:
                if i.startswith('https://vk.com/'):
                    domain = i[15:]
                else:
                    domain = i
                pre_list[domain] = []
                msg.reply(f'{domain} added').send()

            if sender in user_domain_list:
                for i in pre_list:
                    user_domain_list[sender][i] = []
            else:
                user_domain_list[sender] = pre_list

            f = open('user_data', 'wb')
            pickle.dump(user_domain_list, f)
            f.close()

    def remove(self, msg, sender):
        global user_domain_list
        message_body = msg['body'].strip().split()
        if sender in user_domain_list:
            if len(message_body) == 1:
                msg.reply('please enter domain(s) after /rm to remove it or -all to remove all domains').send()
            elif message_body[1] == '-all':
                del user_domain_list[sender]
                msg.reply(f'{sender} domain list was removed').send()
            else:
                message_body = message_body[1:]
                for domain_name in message_body:
                    try:
                        del user_domain_list[sender][domain_name]
                        msg.reply(f'{domain_name} removed').send()
                    except Exception:
                        msg.reply(f'error: cant remove {domain_name}').send()
        else:
            msg.reply(f'{sender} domain list not found therefore cant be removed').send()
        f = open('user_data', 'wb')
        pickle.dump(user_domain_list, f)
        f.close()

    def show(self, msg, sender):
        global user_domain_list
        show_list = []
        for domain in user_domain_list[sender]:
            show_list.append(domain)
        msg.reply('\n'.join(show_list)).send()

    def test(self, msg, sender):
        print('test')
        global user_domain_list
        print(user_domain_list)

    def message_handler(self, msg):
        sender = str(msg['from'])
        if '/' in sender:
            sender = sender[:sender.index('/')]

        if msg['body'].startswith('/add'):
            self.add(msg, sender)

        elif msg['body'].startswith('/up'):
            self.geter(msg, sender)

        elif msg['body'].startswith('/rm'):
            self.remove(msg, sender)

        elif msg['body'].startswith('/show'):
            self.show(msg, sender)

        elif msg['body'].startswith('/t'):
            self.test(msg, sender)

        else:
            self.undefined_command(msg, sender)


def main():
    vinni = Vinni(JID, JID_password)
    vinni.connect()
    vinni.process()


if __name__ == '__main__':
    main()
